import 'package:flutter/material.dart';
import 'package:whale/helper/utils/httputils/net_code.dart';

import '../../../../utils/util.dart';
import '../controller.dart';
import 'state.dart';

abstract class ITabRefreshController<S extends ITabRefreshState>
    extends IRefreshController<S> with GetTickerProviderStateMixin {
  ITabRefreshController();

  String idenPrefix();

  @override
  Future<void> onRefresh() async {
    if (state.title == null || state.tabCtrl == null) {
      await requestForTabTitles();
    }
    return super.onRefresh();
  }

  @override
  void updateBody() {
    update([
      state.updatePageId,
      state.updateLayoutPageId,
    ]);
  }

  void updateTabbar() {
    update([state.updateTabbarId, state.updateTabBarViewId]);
  }

  void updateLayoutTabbarView() {
    update([state.updateLayoutPageId]);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  Future<void> requestForTabTitles();

  @protected
  void setupTabData(List<String>? tabTitles, int initialIndex) {
    if (state.tabCtrl != null) {
      state.tabCtrl?.removeListener(_onTabChange);
    }
    if (tabTitles?.isNotEmpty != true) {
      state.tabCtrl = null;
      return;
    }
    state.setupData(tabTitles);
    state.tabCtrl = TabController(
        initialIndex: initialIndex, length: tabTitles!.length, vsync: this);
    state.tabCtrl!.addListener(_onTabChange);
    state.tabIndex.value = initialIndex;
    updateTabbar();
  }

  void _onTabChange() {
    if (state.tabCtrl?.index == state.tabCtrl?.animation?.value) {
      state.tabIndex.value = state.tabCtrl!.index;

      if (state.page?.records == null) {
        onTabRefresh();
        return;
      }
    }
  }

  Future<void> onTabRefresh() async {
    await onRefresh();
  }

  String get currIden {
    return '${idenPrefix()}-${state.tabCtrl?.index ?? 0}';
  }

  @override
  Future<NetBaseReponse> onRequest({int? current}) async {
    final ctrl = state.subCtrls[currIden];
    if (ctrl == null) {
      return NetBaseReponse.code(code: NetResponseCode.success);
    }
    return ctrl.loadData(pageIndex: current ?? 1);
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    state.tabCtrl?.removeListener(_onTabChange);
    state.tabCtrl?.dispose();
    super.dispose();
  }
}
